package com.xmzgxcl.java202108.util;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

/**
 * Author: venky-ming
 * Date: 2021-08-19 17:40
 **/
public class CheckCodeUtil {
    public static final int WIDTH = 120;
    public static final int HEIGHT = 25;
    public static final int WORDS_NUMBER = 4;

    private CheckCodeUtil(){}

    private static final CheckCodeUtil checkCodeUtil = new CheckCodeUtil();

    public static CheckCodeUtil getInstance(){
        return checkCodeUtil;
    }

    public void getCheckCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //在内存中创建一张图片
        BufferedImage bufferedImage = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_3BYTE_BGR);
        //得到图片
        Graphics graphics = bufferedImage.getGraphics();
        //设置图片的背景色
        setBackGround(graphics);
        //设置图片的边框
        setBorder(graphics);
        //在图片上画干扰线
        drawRandomLine(graphics);
        //在图片上放上随机字符
        String randomNum = drawRandomNum(graphics);
        //将验证码放在session中
        request.getSession().setAttribute("CheckCode",randomNum);
        System.out.println(randomNum);
        //将图片传给浏览器
        ImageIO.write(bufferedImage, "jpg", response.getOutputStream());
    }

    /**
     * 生成随机字符串
     * @param graphics
     * @return
     */
    private String drawRandomNum(Graphics graphics) {
        graphics.setColor(Color.red);
        graphics.setFont(new Font("宋体",Font.BOLD,20));
        String baseCode = "qwertyuiopasdfghjklzxcvbnm0123456789QWERTYUIOPASDFGHJKLZXCVBNM";
        StringBuilder stringBuilder = new StringBuilder();
        String ch ;
        int x = 5;
        for (int i = 0;i<WORDS_NUMBER;i++){
            ch = baseCode.charAt(new Random().nextInt(baseCode.length()))+"";
            stringBuilder.append(ch);
            graphics.drawString(ch,x,20);
            x+=30;
        }
        return stringBuilder.toString();
    }

    /**
     * 干扰线
     * @param graphics
     */
    private void drawRandomLine(Graphics graphics) {
    }

    /**
     * 设置图片边框
     * @param graphics
     */
    private void setBorder(Graphics graphics) {
        graphics.setColor(Color.blue);
        graphics.drawRect(1,1,WIDTH-2,HEIGHT-2);
    }

    /**
     * 设置图片背景
     * @param graphics
     */
    private void setBackGround(Graphics graphics) {
        graphics.setColor(Color.pink);
        graphics.fillRect(0,0,WIDTH,HEIGHT);
    }
}
